<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:faDeviceType:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list">
      <el-table-column label="类型名称" align="center" prop="name" />
      <el-table-column label="类型" align="center" prop="functionType">
        <template slot-scope="{row}">
          <dict-tag :options="dict.type.device_type_type" :value="row.functionType"/>
        </template>
      </el-table-column>
      <el-table-column label="类型代号" align="center" prop="code" show-overflow-tooltip />
      <!-- <el-table-column label="AEP 产品ID" align="center" prop="aepProductId" show-overflow-tooltip/>
      <el-table-column label="AEP 产品KEY" align="center" prop="aepAPIkey" show-overflow-tooltip /> -->
      <el-table-column label="类型枚举" align="center" prop="enumValue">
        <template slot-scope="{row}">
          <dict-tag :options="dict.type.device_type_enum" :value="row.enumValue"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createtimeFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
            v-hasPermi="['system:faDeviceType:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(row)"
            v-hasPermi="['system:faDeviceType:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="类型代号" prop="code">
          <el-input v-model="form.code" placeholder="请输入类型代号" />
        </el-form-item>
        <el-form-item label="类型枚举" prop="enumValue">
          <el-select v-model="form.enumValue" placeholder="请选择类型枚举">
            <el-option
              v-for="(dict,index) in dict.type.device_type_enum"
              :key="('device_type_enum' + index)"
              :label="dict.label"
              :value="Number(dict.value)">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-if="form.id">
          <h2>设备类型AEP信息：</h2>
          <el-row v-for="(item,index) in form.aepinfoList" :key="'aepinfoList' + index">
            <el-col :span="8">
              <el-form-item label="供应商" prop="aepSupplierId">
                <el-select
                  v-model="item.aepSupplierId"
                  placeholder="请选择供应商"
                  clearable 
                  style="width: 240px"
                >
                  <el-option :disabled="getTypeStatus(dict.id,index)"
                    v-for="dict in supplierList"
                    :key="dict.id"
                    :label="dict.supplierName"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="AEP 产品ID" prop="aepProductId">
                <el-input v-model="item.aepProductId" placeholder="请输入AEP 产品ID" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="AEP 产品KEY" prop="aepAPIkey">
                <div class="flex_hcneter">
                  <el-input v-model="item.aepAPIkey" class="flex_flex" placeholder="请输入AEP 产品KEY" />
                  <div style="margin-left:10px;">
                    <el-button type="primary" v-if="form.aepinfoList.length -1 === index" icon="el-icon-plus" @click="addList"></el-button>
                    <el-button type="primary" v-if="form.aepinfoList.length > 1" icon="el-icon-minus" @click="delList(index)"></el-button>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, addFaDevice, updateFaDeviceType, delFaDeviceType,queryFaDeviceType,} from "@/api/config/deviceType";
import { getAllFaSupplier,} from "@/api/config/supplier";
export default {
  name: "DeviceType",
  dicts: ['device_type_enum','device_type_type',],
  data() {
    return {
      supplierList:[],//供应商列表
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "类型名称不能为空", trigger: "blur" }],
        code: [{ required: true, message: "类型代号不能为空", trigger: "blur" }],
        // aepProductId: [{ required: true, message: "AEP 产品ID不能为空", trigger: "blur" }],
        // aepAPIkey: [{ required: true, message: "AEP 产品KEY不能为空", trigger: "blur" }],
        enumValue: [{ required: true, message: "类型枚举不能为空", trigger: "change" }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getTypeStatus(value,index){//禁用重复选择
      return this.form.aepinfoList.find((item,index1)=>item.aepSupplierId == value && index1 != index) ? true : false
    },
    addList(){//添加列表
      this.form.aepinfoList.push({})
    },
    delList(index){//删除列表
      this.form.aepinfoList.splice(index,1)
    },
    async getAllFaSupplier(){//查询所有供应商列表
      let res = await getAllFaSupplier()
      let data = res.data || []
      this.supplierList = data
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      getList(this.queryParams).then(response => {
          let rows = response.rows || []
          this.list = rows
          this.total = response.total || 0;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {pushType:1,};
      this.resetForm("form");
      this.getAllFaSupplier()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目推送管理";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dictId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = "修改项目推送管理";
      let res = await queryFaDeviceType({id:row.id})
      let data = res.data || {}
      let aepinfoList = data.aepinfoList || []
      this.form = {...data,pushType:data.pushType || 1,aepinfoList:aepinfoList.length ? aepinfoList : [{}]};
    },
    getStrNull(str){//判断是否为空
      return str === '' || str === null || str === undefined
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let form = {...this.form}
          if (this.form.id != undefined) {
            let aepinfoList = form.aepinfoList || []
            let flag = false
            aepinfoList = aepinfoList.map(item=>{
              if( this.getStrNull(item.aepSupplierId) || this.getStrNull(item.aepProductId) || this.getStrNull(item.aepAPIkey) ) flag = true
              return {...item,deviceTypeId:form.id,}
            })
            form.aepinfoList = [...aepinfoList]
            if(flag) return this.$modal.msgError("请填写完整设备类型AEP信息");
            updateFaDeviceType(form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFaDevice(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return delFaDeviceType({id:dictIds});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>